package gameobjects;

import java.util.LinkedList;
import java.util.Queue;
import interfaces.Controllable;
import abstracts.Level;
import abstracts.Task;

public class TaskQueue implements Controllable {
    private Queue<Task> queue;
    private Level level;
    private Task now;

    public TaskQueue() {
        queue = new LinkedList<Task>();
    }

    public TaskQueue(TaskQueue copy) {
        queue = new LinkedList<Task>(copy.queue);
    }

    public void add(Task task) {
        queue.add(task);
    }

    public void run(Level level) {
        this.level = level;
        level.add(this);
        next();
    }

    public void next() {
        Task next = queue.poll();
        if (next == null) {
            // All done
            level.remove(this);
        } else {
            now = next;
            level.add(now);
        }
    }

    @Override
    public void control() {
        if (now != null && now.isDone()) {
            level.remove(now);
            next();
        }
    }
}
